package com.limingru.online_class.controller;

import com.limingru.online_class.common.Result;
import com.limingru.online_class.common.ResultGenerator;
import com.limingru.online_class.common.ServiceResultEnum;
import com.limingru.online_class.controller.param.LoginUserInfo;
import com.limingru.online_class.domain.User;
import com.limingru.online_class.domain.vo.UserVO;
import com.limingru.online_class.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/pri/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("register")
    public Result register(@RequestBody Map<String, String> userInfo) {
        String saveResult = userService.save(userInfo);
        return ServiceResultEnum.SUCCESS.getText().equals(saveResult )
                ? ResultGenerator.generateSuccessResult()
                : ResultGenerator.generateFailResult(saveResult);
    }

    @PostMapping("login")
    public Result login(@RequestBody LoginUserInfo loginUserInfo) {
        String result = userService.findUser(loginUserInfo);
        return ServiceResultEnum.PHONE_OR_PWD_ERROR.getText().equals(result) || ServiceResultEnum.PHONE_OR_PWD_NOT_EMPTY.getText().equals(result)
                ? ResultGenerator.generateFailResult(result)
                : ResultGenerator.generateSuccessResult(result);
    }

    @GetMapping("userInfo")
    public Result getUserInfo(HttpServletRequest request) {
        Integer id  = (Integer) request.getAttribute("userId");
        String name = (String) request.getAttribute("userName");
        UserVO userVO = userService.listUserByIdAndName(id, name);
        if (userVO != null) {
            return ResultGenerator.generateSuccessResult(userVO);
        }
        return ResultGenerator.generateFailResult();
    }
}
